package com.jack.leetcode.eachproblem_2020;

import java.util.LinkedList;
import java.util.Stack;

public class 移掉k位数字 {

    public static void main(String[] args) {
        System.out.println(removeKdigits("1432219", 3));
        System.out.println(removeKdigits("10200", 1));
    }

    public static String removeKdigits(String num, int k) {
        int n = num.length();
        if(n == k){
            return "0";
        }
        int newLength = n - k;
        StringBuilder result = new StringBuilder();
        Stack<Character> stack = new Stack<>();
        for(char c : num.toCharArray()){
            while(k != 0 && !stack.isEmpty() && stack.peek() > c){
                stack.pop();
                k -= 1;
            }
            stack.add(c);
        }
        while(!stack.isEmpty() && stack.firstElement() == '0'){
            stack.remove(0);
        }
        if(stack.isEmpty()){
            return "0";
        }
        stack.stream().limit(newLength).forEach(s -> result.append(s));
        return result.toString();
    }

    public void moveZeroes(int[] nums) {
        int n = nums.length;
        for(int i = 0;i < n;i++){
            if(nums[i] == 0){
                int index = -1;
                for(int j = i + 1;j < n;j++){
                    if(nums[j] != 0){
                        index = j;
                        break;
                    }
                }
                if(index != -1){
                    int tmp = nums[index];
                    nums[index] = 0;
                    nums[i] = tmp;
                }
            }
        }
    }
}
